String.prototype.trim=function(){
	return this.replace(/^\s*|\s*$/g, "");
};
//record the data item construnction which contains mids but not contains origin mids
var bases = new Array();
var ASSIGN = "assign";
var MERGE = "merge";
var CHAIN = "chain";
var STATUS_CONFLICT = "conflict";
var STATUS_REMOVE = "removed";
var STATUS_NEW_CHILD = "newchild";
var STATUS_UPDATE = "update";
var STATUS_NOAUTHORITY = "noauthority";
var STATUS_OK="ok";

//used to check whether to pop the entity object in the bases object
var VALUE_CHANGE="VC";
var VALUE_REMAIN ="VR";

var customDMID =0;
var originDMID =1;

//store mid to entity table
var hashMap = new HashMap();

var count ;
var displayLang;//must be the name "displayLang" (for fetch values)
var etype ;
var eid ;
var vid ;
var genre;
var isInner ;
var groupID;
var editClassID;
var ve_serv;
var value_type;
var query_item_id;

function Entity(mid,dmtype,dmid,inverse){
	//the id of Entity which is one of the dms' mids
	this.mid = mid;
	this.getMId = function(){
		return this.mid;
	};
	this.dmtype = dmtype;
	this.getDMType = function(){
		return this.dmtype;
	};
	
    this.dmid = dmid;
    this.getDMID = function(){
    	return this.dmid;
    };
    this.inverse = inverse;
    this.getInverse = function(){
    	return this.inverse;
    };
    
    this.origin = true;
    this.isOrigin= function(){
    	return this.origin;
    };
    this.setOrigin = function(origin){
    	this.origin = origin;
    };
}

$(document).ready(function() {
	/*disable language setting during the view editing*/
	$("#set-option").unbind("click");
	ve_serv = WEBAPP+"viewEdit";
	//store all the new data members created
	count = eval($("#count").val()) ;
	displayLang = $("#display-lang").val();//must be the name "displayLang" (for fetch values)
	etype = parseInt($("#etype").val());
	eid = parseInt($("#eid").val());
	vid = $("#vid").val();
	genre = $("#genre").val();
	isInner = $("#isInner").val();
	groupID = $("#gid").val();
	editClassID = $("#cid").val();
	value_type = $("#vtype").val();
	query_item_id =$("#dmid").val();
	
	$("a.back").click(function(){
		var location = WEBAPP+"views/evedit.jsp?genre="+genre+"&eid="+eid+"&gid="+groupID+"&i="+isInner
			+"&cid="+editClassID+"&f=dmedit"+"&lang="+displayLang;
		if(vid!="0")
			location = location +"&vid="+vid;
		window.location= location;
	});
	
    if(query_item_id=="-1"){
    	newQueryItem();
    }else{
    	editQueryItem();
    }
	
/*filter data items*/
	$("span.combo-arrow").mouseover(function(){
		$(this).addClass("combo-arrow-hover");
	});
	
	$("span.combo-arrow").mouseout(function(){
		$(this).removeClass("combo-arrow-hover");
	});
	
	$("span.combo-arrow").click(function(){
		$(".filter-box").show();
	});
	
	$(".filter-box .item").mouseover(function(){
		$(this).addClass("bh") ;
	});
	
	$(".filter-box .item").mouseout(function(){
		$(this).removeClass("bh") ;
	});	
	
/*edit button of tools*/
	$(".backchain").live("click",function(event){
		event.stopPropagation();
		var li = $(this).parent().parent().parent();
		var xxx = li.find(".hidden .li-container-history:last");
		li.find(".li-container").remove();
		xxx.removeClass("li-container-history");
		xxx.addClass("li-container");
		li.prepend(xxx);
		if(li.find(".hidden .li-container-history").length==0){
		$(this).remove();
	}
	});
	
/*end:edit button of tools*/
	
/* init :show the exist data item in the left and right panel*/
	init();
	
	$(".dms .titlebar").live("click",function(){
		$(this).find("a.status").toggleClass("collapse");
		$(this).parent().find(".content").toggle('fast');
	});
	
	 $(".pvalue li,.lvalue li,.hitem").live("mouseover",function(){
		 $(this).addClass("bh");
	 });
	   
	 $(".pvalue li,.lvalue li,.hitem").live("mouseout",function(){
		 $(this).removeClass("bh");
	 });
	 
     $("a.close").live("click",function(event){
		$(this).parent().parent().parent().remove();
		event.stopPropagation();
	});	 
/*end:init :show the exist data item in the left and right panel*/

/*delete data item*/
       $(".del_op").live("click",function(){
    	   var container= $(".edit_panel");
    	   var dmid = container.attr("dmid");
    	   var dmtype = container.attr("dmtype");
    	   if(dmid<0){
    		   clearHistory();
    		   newQueryItem();
    	   }else{
    		    var dialog = $(".warning");
    			var dialog_title;
    			if (displayLang == "en") {
    				dialog_title = "Warning";
    			} else if (displayLang == "zh") {
    				dialog_title = "警告";
    			}
    			dialog.show();
    			var yesLabel;
    			if(displayLang=="en"){
    				yesLabel ="Yes";
    			}else if(displayLang=="zh")
    				yesLabel = "是";
    			var noLabel;
    			if(displayLang=="en"){
    				noLabel ="NO";
    			}else if(displayLang=="zh")
    				noLabel = "否";
    			dialog.dialog({
    				title : dialog_title,
    				modal : true,
    				width : 500,
    				buttons : [
    						{
    							text :yesLabel,
    							click : function() {
    								dialog.dialog('close');
    					    		var res = deleteDM(dmtype,dmid);
    								if(res){
    									if(displayLang=="en")
    										 $.messager.alert('Info','The query item is being edited. Please retry later!','info');
    									 else if(displayLang=="zh")
    										 $.messager.alert('提示','查询项正在被编辑。请稍后再试!','info');
    								}else{
        					    		$("div.li-container[dmtype="+dmtype+"][dmid="+dmid+"]").parent().remove();
        					    		clearHistory();
        					    		newQueryItem();
    								}
    							}
    						},
    						{
    							text : noLabel,
    							click : function() {
    								dialog.dialog('close');
    							}
    						} ]
    			});
    	   }
       });	   
/*end:delete data item*/

/*save data item*/
       $(".save_op").live("click",function(){
    	   if($(this).hasClass("disabled"))
    		   return;
    	   var box = $(".edit_panel");
    	   var name = $(".dmName").val();
    	   if(name.trim()==""){
    			if(displayLang=="en"){
    				$.messager.alert('Error','Please enter the query item name!','error');
    			}else if(displayLang=="zh"){
    				$.messager.alert('错误','请输入查询项名字!','error');
    			}
    		   return;
    	   }
    	   var dmtype=box.attr("dmtype");
    	   var dmid=box.attr("dmid");
    	   var vtype = box.attr("vtype");
    	   var result = storeDM(name,dmtype,dmid,vtype);
    	   var status = result["status"];
    	   if(status ==STATUS_CONFLICT){
    			if(displayLang=="en"){
    				$.messager.alert('Error','The query item name has existed!','error');
    			}else if(displayLang=="zh"){
    				$.messager.alert('错误','查询项名称已经存在!','error');
    			}
    			return ;
    	   }else if(status ==STATUS_REMOVE ){
    			if(displayLang=="en"){
    				$.messager.alert('Error','Sorry. The query item has been removed elsewhere!','error',function(){
    					var location = WEBAPP+"views/evedit.jsp?genre="+genre+"&eid="+eid+"&gid="+groupID+"&i="+isInner
    					+"&cid="+editClassID+"&f=dmedit"+"&lang="+displayLang;
    				    if(vid!="0")
    					   location = location +"&vid="+vid;
    				    window.location= location;
    				});
    			}else if(displayLang=="zh"){
    				$.messager.alert('错误','抱歉，该查询项在别处已被删除!','error',function(){
    					var location = WEBAPP+"views/evedit.jsp?genre="+genre+"&eid="+eid+"&gid="+groupID+"&i="+isInner
    					+"&cid="+editClassID+"&f=dmedit"+"&lang="+displayLang;
    				    if(vid!="0")
    					   location = location +"&vid="+vid;
    				    window.location= location;
    				});
    			}
    			$(".ruleList").html("");
    			$(".tmpRuleList").html("");
    			box.remove();
    			return ;
    	   }else if(status ==STATUS_NOAUTHORITY ){
	   			if(displayLang=="en"){
					$.messager.alert('Info','The query item is being edited elsewhere. Please retry later!','info');
				}else if(displayLang=="zh"){
					$.messager.alert('提示','查询项在别处正被编辑。请稍后再试!','info');
				}
				return ;
    	   }else if(status==STATUS_OK){
    		   var detail_status = result["detail_status"];
    		   if(detail_status==STATUS_NEW_CHILD){
   	      			var dtype = result["dmtype"];
   	      			var did = result["dmid"];
   	      			box.attr("dmtype",dtype);
   	      			box.attr("dmid",did);
       	        }else if(detail_status==STATUS_UPDATE){
       	        	var object =  $("div.li-container[dmtype="+dmtype+"][dmid="+dmid+"]");
       	        	object.find(".title").html(name);
       	        	object.find(".content").html("");
       	        	object.find(".content").append(box.find(".content ul").clone());
       	        }
    		   
    		   var dmtype = $(".edit_panel").attr("dmtype");
  			   var dmid = $(".edit_panel").attr("dmid");
  			   var vtype = $(".edit_panel").attr("vtype");
    		   clearHistory();
    			/*edit buttons*/
    		    $(".save_op").addClass("disabled");
    		   
    			if(dmid=="-1"){
    			    newQueryItem();
    			 }else{
    				var inverse =  0;
    				var func  = 0;
    				createEditDMBox(name,dmtype,dmid,inverse,func,vtype);
    			    box = $(".ruleList");
    			    addRules(dmid,box,true);
    			 }
    	   }
    	   
       });
/*end:save data item*/
	
/*data item chain*/
	$("a.chain").live("click",function(event){
		addRestoreButtonToBar($(this).parent());
		//var span = $("<img class='header-chain' src='/sview/icons/chain_arrow.png'></img>");
		//span.insertAfter($(this).parent().find(".title"));
		$(this).parent().find(".title").addClass("chainTitle");
		var $liBox = $(this).parent().parent();
		
		var array = new Array();
		$liBox.find(".pvalue li").each(function(){
			var etype= $(this).attr("etype");
			var eid = $(this).attr("eid");
			if(etype==URI_ENTITY_STR){
				array.push(eid);
			}
		});
		
		
		$liBox.find(".pvalue").hide();
		$liBox.find(".op").hide();
		$liBox.parent().addClass("chaining");
		var ul=$("<ul class='lvalue'></ul>");
		
		getAvailableChain(ul,array);
		
		$(this).parent().parent().find(".content").prepend(ul);
		$(this).remove();
		event.stopPropagation();
	});
	
	$("a.restore").live("click",function(event){
         restore($(this).parent().parent());
         event.stopPropagation();
	});
	
	$("a.lchain,.lvalue a.linkName").live("click",function(){
		var vtype  = $(this).parent().find(".linkName").attr("vtype");
	    var container = createChainLink(vtype);
	    var $content = $(this).parent().parent().parent();
	    
	    var li = $content.parent().parent();
	    
	    var efrom = $content.parent();
	    var entity_from = new Entity($(efrom).attr("mid"),$(efrom).attr("dmtype"),$(efrom).attr("dmid"),$(efrom).attr("inverse"));
	    var title1 = efrom.find(".titlebar .title").html();
	    var eto =  $(this).parent().find("a");
	    var entity_to = new Entity($(eto).attr("mid"),$(eto).attr("dmtype"),$(eto).attr("dmid"),$(eto).attr("inverse"));
	    var title2=eto.html();
	    
	    var title = title1+"_"+title2;
	    container.find(".titlebar .title").html(title);
	   
	    restore($content.parent());
	    var backLiContainer = li.find(".li-container");
	    backLiContainer.removeClass("li-container");
	    backLiContainer.addClass("li-container-history");
	    if(li.find(".hidden").length==0){
    	var hidden = $("<div class='hidden'></div>");
    	li.append(hidden);
       }
       li.find(".hidden").append(backLiContainer);
	    
	    //mid
	    var mid = getMID();
	    li.prepend(container);
	    li.find(".li-container").attr("mid",mid);
	    var valueType = $(eto).attr("vtype");
	    li.find(".li-container").attr("vtype",valueType);
	    li.find(".li-container").attr("inverse",0);
	    li.find(".li-container").attr("arity",2);
	    li.find(".li-container").removeClass("origin");
	    var makeMethod =MAKE_METHOD_CHAIN;
	    //container,name,author,valueType,makeMethod,entity_from,entity_to,displayLang
	    createTMPChain( li.find(".li-container"),title,groupID,valueType,makeMethod,entity_from,entity_to,displayLang);
	    addBackChainButtonToBar(li.find(".li-container .titlebar"));
	    
	    var status ="undownloaded" ;
	    var dmtype = parseInt(li.find(".li-container").attr("dmtype"));
	    var dmid = parseInt(li.find(".li-container").attr("dmid"));
	    var inverse = parseInt(li.find(".li-container").attr("inverse"));
	    var con = $(container).find(".pvalue");
	    fetchValues(displayLang,con,dmtype,dmid,inverse,genre,eid,status);
	});
/*end: data item chain*/
	
	/*add datamember to view*/
	$(".addbtn").live("click",function(event){
		if($(this).hasClass("disabled"))
			return false;
		var addElement = $(this).parent().parent().parent();
		restore(addElement.find(".li-container"));
        var flag =  dropFunction($(".vcontent"),addElement);
        event.stopPropagation();
        
        //add the rule
        var addPredName = addElement.find(".titlebar .title").html();
        var dmtype = addElement.find(".li-container").attr("dmtype");
        var dmid = addElement.find(".li-container").attr("dmid");
        var mid  = addElement.find(".li-container").attr("mid");
        
        var hasOtherRule = true;
        if(addElement.find(".li-container").hasClass("origin")){
        	hasOtherRule = false;
        }
        addTmpRule(dmtype,dmid,addPredName,hasOtherRule,mid);
        $(".unsavedBox").show();
	});
	
	/*start: rule list */
	$(".del_rule_op").live("click",function(){
		var box = $(this).parent();
		var mid = $(this).attr("mid");
		if(!box.hasClass("saved_rule")){
			var dmid  = box.attr("dmid");
			var hidden = $(".vcontent .hidden");
			var dmtype = box.attr("dmtype");
			
			var array = hidden.find("div[dmtype="+dmtype+"][dmid="+dmid+"]");
			//可能重复赋值，所以有多个
			if(array.length>0){
				$(array[0]).remove();
			}
			
			var ul = $(".vcontent ul.pvalue").html("");
			hidden.find("li").each(function(){
				var etype = $(this).attr("etype");
				var eid = $(this).attr("eid");
			 	var xx=$(ul).find("li[etype="+etype+"][eid="+eid+"]").length;
			   	if(xx>0)
			         return;
			   	else
			   	  $(ul).append($(this).clone());
			 });
			 $(ul).find("li.final").removeClass("final");
			 $(ul).find("li:last").addClass("final");
			 
			 /*edit buttons*/
			 $(".save_op").removeClass("disabled");
			 
			 /*history*/
			 hashMap.remove(mid);
			 
				
			box.remove();
			if($(".tmpRuleList>div").length==0){
				$(".unsavedBox").hide();
			}
		}else{
			var dialog = $(".warning.rule");
			var dialog_title;
			if (displayLang == "en") {
				dialog_title = "Warning";
			} else if (displayLang == "zh") {
				dialog_title = "警告";
			}
			dialog.show();
			var yesLabel;
			if(displayLang=="en"){
				yesLabel ="Yes";
			}else if(displayLang=="zh")
				yesLabel = "是";
			var noLabel;
			if(displayLang=="en"){
				noLabel ="NO";
			}else if(displayLang=="zh")
				noLabel = "否";
			dialog.dialog({
				title : dialog_title,
				modal : true,
				width : 500,
				buttons : [
						{
							text :yesLabel,
							click : function() {
								dialog.dialog('close');
								var rowIDs = new Array();
								box.find("input").each(function(){
									rowIDs.push($(this).val());
								});
								var dmtype = $(".edit_panel").attr("dmtype");
								var dmid = $(".edit_panel").attr("dmid");
								if(dmid>0){
									var res = deleteRule(dmtype,dmid,rowIDs);
									if(res){
										if(displayLang=="en")
											 $.messager.alert('Info','The query item is being edited. Please retry later!','info');
										 else if(displayLang=="zh")
											 $.messager.alert('提示','查询项正在被编辑。请稍后再试!','info');
									}else{
										var ruleBox = $(".ruleList");
										ruleBox.html("");
										addRules(dmid,ruleBox,true);
										var ul = $(".edit_panel").find(".pvalue").html("");
										var status = "undownloaded" ;
										var inverse = 0;
										dmtype = parseInt(dmtype);
										dmid  = parseInt(dmid);
										fetchValues(displayLang,ul,dmtype,dmid,inverse,genre,eid,status,false);
										$(".vcontent").find(".hidden .saved").html(ul.html());
										$(".vcontent .hidden>div").each(function(){
											if(!$(this).hasClass("saved")){
												$(this).find("li").each(function(){
													var etype = $(this).attr("etype");
													var eid = $(this).attr("eid");
												 	var xx=$(ul).find("li[etype="+etype+"][eid="+eid+"]").length;
												   	if(xx>0)
												         return;
												   	else
												   	  $(ul).append($(this).clone());
												});
											}
										});
										$(ul).find("li.final").removeClass("final");
										$(ul).find("li:last").addClass("final");
										
										 /*edit buttons*/
										 $(".save_op").removeClass("disabled");
									}
								}
							}
						},
						{
							text : noLabel,
							click : function() {
								dialog.dialog('close');
							}
						} ]
			});
		}	
	});
	/*end: rule list*/
	
});

function addAddButtonToBar(bar){
	var button = $('<button class="addbtn btn btn-primary btn-small"></button>');
	if(displayLang=="en"){
		button.html("Assign");
    }else{
    	button.html("赋值");
    }
	bar.append(button);
}

function addChainButtonToBar(bar){
	var button = $('<a class="easyui-linkbutton chain" plain="true" iconCls="icon-chain" '+
	'href="javascript:void(0)"></a>');
 	var op_title= null;
	if(displayLang=="en")
		op_title = "Chain";
	else if(displayLang=="zh")
		op_title = "链接"; 	
	button.attr("title",op_title);
	button.linkbutton();
	bar.append(button);	
}

function addBackChainButtonToBar(bar){
	var button = $('<a class="easyui-linkbutton backchain" plain="true" iconCls="icon-back" '+
	'href="javascript:void(0)"></a>');
 	var op_title= null;
	if(displayLang=="en")
		op_title = "Back to last step";
	else if(displayLang=="zh")
		op_title = "返回前一步"; 	
	button.attr("title",op_title);
	button.linkbutton();
	if(bar.find("a.chain").length==0){
		button.addClass("single");
	}
	bar.append(button);	
}

function createChainLink(vtype){
     var container = $("<div class='li-container origin'></div>");
     var titlebar = null;
     if(vtype=="0"){
    	 titlebar = $("<div class='titlebar'><span class='loading'></span><a class='status'></a><span class='title'></span>"+
    		 "<a class='close' href='javascript:void(0)'></a>" +
     		" </div>");
    	 addChainButtonToBar(titlebar);
     }else{
    	 titlebar =  $("<div class='titlebar'><span class='loading'></span><a class='status'></a><span class='title'></span>"+
        		 "<a class='close' href='javascript:void(0)'></a>" +
  		"</div>");
     }
     addAddButtonToBar(titlebar);
     container.append(titlebar);
     
     var content = $("<div class='content'></div>");
     var ul = $("<ul class='pvalue'></ul>");
     content.append(ul);
     container.append(content);
     return container;     
}

function addDMToLeftPanel(dmtype,dmid,arity,inverse,vtype,funct,hasAuthor,name,flag){
	$(".dmList").html("");
	var li = $("<li class='prop'></li>");
	$(".dmList").prepend(li);
	var div  = $("<div class='li-container origin'></div>");
	li.append(div);
	div.attr("inverse",inverse);
	div.attr("vtype",vtype) ;
	
	var mid = getMID();
	div.attr("mid",mid);
	div.attr("dmtype",dmtype);
	div.attr("dmid",dmid) ;
	div.attr("arity",arity);
	div.attr("editable",hasAuthor);
	
	if(funct==1){
		li.addClass("func");
		if(vtype==1){
			li.addClass("func_literal");
		}
	}
	
    var titleDiv = $("<div class='titlebar'></div>");
    div.append(titleDiv);
    var spanLoading = $("<span class='loading'></span>");
    titleDiv.append(spanLoading);
    var span = $("<span class='title'></span>");
    span.text(name);
    addExpandButtonToBar(titleDiv);
    titleDiv.append(span);
    if(vtype==0){
    	addChainButtonToBar(titleDiv) ;
    }
    
    var content = $("<div class='content'></div>");
	var pvalue = $("<ul class='pvalue'></ul>");
    div.append(content) ;
	content.append(pvalue);
	
	var opBox = $("<div class='dm_op_box'></div>");
	div.append(opBox);
	addAddButtonToBar(opBox);
	
    var status = "undownloaded" ;
    if(flag)
    	fetchValues(displayLang,pvalue,dmtype,dmid,inverse,genre,eid,status,false);
	return li;
}

function addExpandButtonToBar(bar){
	var button = $('<a class="status"></a>');
	bar.append(button);
}

function addRemoveButtonToBar(bar){
	var button = $('<a class="close"></a>');
 	var op_title= null;
	if(displayLang=="en")
		op_title = "Remove";
	else if(displayLang=="zh")
		op_title = "移除"; 	
	button.attr("title",op_title);
	$(bar).append(button);	
}

function addRestoreButtonToBar(bar){
	var button = $('<a class="restore" '+
	'href="javascript:void(0)"></a>');
 	var op_title= null;
	if(displayLang=="en")
		op_title = "Restore";
	else if(displayLang=="zh")
		op_title = "还原"; 	
	button.attr("title",op_title);
	bar.append(button);	
	
	bar.find("a.backchain").hide();
}

function addSetButtonToBar(bar){
	var button = $('<a class="fset"></a>');
 	var op_title= null;
	if(displayLang=="en")
		op_title = "Single Valuedness Setting";
	else if(displayLang=="zh")
		op_title = "单值性设置"; 	
	button.attr("title",op_title);
	bar.append(button);	
}

function addTmpRule(dmtype,dmid,addPredName,hasOtherRule,mid){
	var box = $(".tmpRuleList");
	var item = $("<div class='item'></div>");
	 box.append(item);
	 //表示肯定是当前编辑query item
	 item.addClass("target");
	 
	//add delete op
	var delRule = $("<a class='del_rule_op'><span class='del_span'></span></a>");
	//通过mid来控制内存中hashMap
	delRule.attr("mid",mid);

	if(displayLang=="en"){
		delRule.attr("title","Delete this assignment");
	}else if(displayLang=="zh"){
		delRule.attr("title","删除这个赋值");
	}
	item.append(delRule);
	item.attr("dmid",dmid);
	item.attr("dmtype",dmtype);
	
    
    /*start: head*/
    var dmName = $(".dmName").val().trim();
	var head = {"isInner":true,"title":dmName,"label":dmName,"args":["?x","?y"]};
	var spanHeader = $("<span class='ruleHead'></span>");
	item.append(spanHeader);
	var headatomSpan = createAtomSpan(head);
	spanHeader.append(headatomSpan);
	//rule sign
	var spanSign = $("<span class='sign'>&nbsp;:-&nbsp;</span>");
	spanHeader.append(spanSign);
	/*end:rule head*/
		 
	/*start: rule body*/
	var spanBody =$("<span class='ruleBody'></span>");
	item.append(spanBody);
	if(!hasOtherRule){
		var bodyatom = {"isInner":true,"title":addPredName,"label":addPredName,"args":["?x","?y"]};
		var body = [bodyatom];
	    for(k=0;k<body.length;k++){
			var bodyAtom = body[k];
			var bodyatomSpan  = createAtomSpan(bodyAtom);
			spanBody.append(bodyatomSpan);
			if(k<body.length-1)
				spanBody.append($("<span>&nbsp;,&nbsp;</span>"));
		}
		var spanFullStop  = $("<span>&nbsp;.</span>");
		spanBody.append(spanFullStop);
	}else{
		/*表示有相应定义规则。add the rule of the assignment definition*/
		var ruleitem = 	getRule(dmid);	
		if($(ruleitem).find(".ruleBody").length>0){
			spanBody.html($(ruleitem).find(".ruleBody").html());
		}
	}
	/*end:rule body*/
}

function addTitleToBar(title,bar){
	bar.attr("title",title);
}

/**
 * clearHistory, saveHistory are related.
 * They also deals with in memory Entitiy objects
 */

function clearHistory(){
	hashMap.clear();
	bases = new Array();
	$(".vcontent").html("");
	$(".ruleList").html("");
	$(".unsavedBox").hide();
	$(".tmpRuleList").html("");
}

//from:content: <div class='content'>, container: content's container 
function copyContent(content,container){
	container.append(content);
}


/**
 * @param left.belong to li-container ,it shouled be cloned
 * @param vcontent. the .vcontent element 
 */
function copyFromLeftToRight(left,vcontent){
	var container = $(vcontent).find(".vbody .content");
	container.html("");
	
	var mid = left.attr("mid");
	var epanel = $(vcontent).find(".edit_panel");
	$(epanel).attr("inverse",left.attr("inverse"));
	$(epanel).attr("vtype",left.attr("vtype"));
	$(epanel).attr("arity",left.attr("arity"));
	var name = $(left).find(".titlebar .title").html();
	
	/*start:store value map*/
	var hidden = $(".vcontent .hidden");
	var dmdiv = $("<div></div>").appendTo(hidden);
	dmdiv.attr("dmtype",$(left).attr("dmtype"));
	dmdiv.attr("dmid",$(left).attr("dmid"));
	dmdiv.html(left.parent().find(".li-container .content ul.pvalue").html());
	/*end:store value map*/
	
	copyContent(left.parent().find(".li-container .content ul.pvalue").clone().show(),container) ;
}


/**
 * create a new edit data item box 
 * @param name. data item name. If a new empty data item is created, the name is untitled/未命名
 * @param dmtype. data item type. If less than 0, it means a new emtpy data item is created
 * @param dmid. data item id. If less than 0, it means a new empty data item is created
 * @param inverse. If a new emtpy data item is created, inverse is 0;
 * @param func. If a new emtpy data item is created, func is 0;
 * @param vtype. If a new emtpy data item is created, vtype is 0;
 */
function createEditDMBox(name,dmtype,dmid,inverse,func,vtype){
	$(".vcontent").html("");
	var outerBox = $(".vcontent");
	var edit_panel = $('<div class="edit_panel"></div>');
	outerBox.append(edit_panel) ;
	edit_panel.attr("dmtype",dmtype);
	edit_panel.attr("dmid",dmid);
	edit_panel.attr("inverse",inverse);
	edit_panel.attr("func",func);
	edit_panel.attr("vtype",vtype);
	var dmName = $(".dmName");
	dmName.val(name);
	var vbody = $('<div class="vbody"></div>');
	edit_panel.append(vbody) ;
	var wrapper = $('<div class="content"></div>');
	var pvalue = $('<ul class="pvalue"></ul>');
	wrapper.append(pvalue) ;
	vbody.append(wrapper) ;
	var dmtype  = parseInt(edit_panel.attr("dmtype")) ;
    var dmid =  parseInt(edit_panel.attr("dmid")) ;
    var inverse =  parseInt(edit_panel.attr("inverse")) ;
    var status = "undownloaded" ;
    
    var hidden = $("<div class='hidden'></div>").appendTo($(".vcontent"));
    
    if(dmtype>=0&&dmid>=0){
    	fetchValuesShowStatus(displayLang,pvalue,dmtype,dmid,inverse,genre,eid,status,false);
    	var savedDiv = $("<div class='saved'></div>").appendTo(hidden);
    	savedDiv.html(pvalue.html());
    }
}

function  createTMPChain( container,name,groupID,valueType,makeMethod,entity_from,entity_to,displayLang){
   var data={};
   data["name"] = name;
   data["groupID"] = groupID;
   data["vtype"] = valueType;
   data["makeMethod"] = makeMethod;
   data["lang"] = displayLang;
   data["isInner"] = isInner;
   data["classID"] = editClassID;
	 
  var base=new Array();
  var from ={};
  from["type"] = entity_from.getDMType();
  from["id"] = entity_from.getDMID();
  from["inverse"] = entity_from.getInverse();
  base.push(from) ;
  var to ={};
  to["type"] = entity_to.getDMType();
  to["id"] = entity_to.getDMID();
  to["inverse"] = entity_to.getInverse();
  base.push(to) ;
  
  data["base"] = base;
  
 data =  JSON.stringify(data);
 data ="createTmpChain="+encodeURIComponent(data);
 
 $.ajax({
 	  url:ve_serv,
 	  async:false,
 	  data:data,
 	  dataType:"json",
 	  type:"post",
     success:function(result){
   	  var dmtype = result["dmtype"] ;
   	  var dmid = result["dmid"];
   	  var inverse = result["inverse"] ;
       var fname = result["name"];
   	  $(container).attr("dmtype",dmtype);
   	  $(container).attr("dmid",dmid);
   	  $(container).attr("inverse",inverse);
     }
   });
}

function deleteDM(dmtype,dmid){
	 var data={};
	 data["dmtype"] = dmtype;
	 data["dmid"] = dmid;
	 data["isInner"] = isInner;
	 data["classID"] = editClassID;
	 data["userName"] =getUser();
	 data =  JSON.stringify(data);
	 data ="deldm="+encodeURIComponent(data);
	 var res = 0;
	 $.ajax({
	   	  url:ve_serv,
	   	  async:false,
	   	  data:data,
	   	  dataType:"text",
	   	  type:"post",
	   	  success:function(data){
	   		  if(data=="noauthority"){
	   			  res = 1;
	   		  }
	   	  }
	 });
	 
	 return res;
}

function deleteRule(dmtype,dmid,rowIDs){
	 var data={};
	 data["dmtype"] = dmtype;
	 data["dmid"] = dmid;
	 data["isInner"] = isInner;
	 data["classID"] = editClassID;
	 data["rowIDs"] = rowIDs;
	 data["userName"] =getUser();
	 data =  JSON.stringify(data);
	 data ="delrule="+encodeURIComponent(data);
	 var res = 0;
	 $.ajax({
	   	  url:ve_serv,
	   	  async:false,
	   	  data:data,
	   	  dataType:"text",
	   	  type:"post",
	   	  success:function(data){
	   		  if(data=="noauthority"){
	   			  res = 1;
	   		  }
	   	  }
	 });
	 
	 return res;
}

/*add left panel to right panel
 * @param dropEle:the .vcontent element
 * @param dragEle:the li.prop element
 * */
function dropFunction(dropEle,dragEle){
     if($(".vcontent").html()==""){
    	 //UI提示
    	 return;
     }
	  //copy everything contains mid origin status
      var dragContainer = $(dragEle).find(".li-container");
  	  if(!$(dragContainer).hasClass("origin")&&$(dragContainer).find(".pvalue>li").length==0){
  		 //UI提示
  		  return;
	  }
  	   var oldname = $(dropEle).find(".dm_name").html();
       var pvalue = $(dropEle).find(".vbody .pvalue").clone();
       var mdiv = $(dragEle).find(".li-container");
       var entity = new Entity(mdiv.attr("mid"),mdiv.attr("dmtype"),mdiv.attr("dmid"),mdiv.attr("inverse"));
  	   var isorigin =  mdiv.hasClass("origin");
      //see if merge
      if(($(dropEle).find(".edit_panel").attr("dmid")<0)&&($(dropEle).find(".pvalue>li").length==0)){
    	  copyFromLeftToRight(dragContainer,dropEle);
      }else{
    	  merge(dropEle,dragContainer);
      }
      
      /*edit buttons*/
      $(".save_op").removeClass("disabled");
      
      /*save history*/
      entity.setOrigin(isorigin);
      saveHistory(entity);
}

function fetchValueByContainer(DivContainer){
	  var dmtype  = parseInt(DivContainer.attr("dmtype")) ;
      var dmid =  parseInt(DivContainer.attr("dmid")) ;
      var inverse =  parseInt(DivContainer.attr("inverse")) ;
      var status = "undownloaded" ;
      fetchValues(displayLang,DivContainer.find(".pvalue"),dmtype,dmid,inverse,genre,eid,status);
}

function filterDMByBackward(lang,etype,eid){
	$(".dms .dmList").html("");
	 var data={};
	 data["lang"] = lang;
	 data["eid"] = eid;
	 data["etype"] = etype;
	 data =  JSON.stringify(data);
	 data ="backward="+encodeURIComponent(data);
	 $.ajax({
	  	  url:ve_serv,
	  	  async:true,
	  	  data:data,
	  	  dataType:"json",
	  	  type:"post",
	      success:function(result){
	    	 $(".dms .dmList").html("");
	          var containers = new Array();
//	    	  for(i=0;i<result.length;i++){
	          for(i=result.length-1;i>=0;i--){
	    		var item = result[i];
			    var dmtype = item.dmtype;
			    var dmid = item.dmid;
			    var inverse = item.inverse;
			    var name = item.name;
			    var vtype = item.vtype;
			    var arity = item.arity;
			    var funct = item.functional;
			    var hasAuthor =item.hasAuthor; 
			    var li = addDMToLeftPanel(dmtype,dmid,arity,inverse,vtype,funct,hasAuthor,name,0) ;
			    containers.push(li) ;
	    	  }
	    	  for(i=0;i<containers.length;i++){
	    		  fetchValueByContainer(containers[i].find(".li-container"),eid);
	    	  }
	      }
	    });
}

function filterDMByForward(lang,etype,eid){
	$(".dms .dmList").html("");
	 var data={};
	 data["lang"] = lang;
	 data["eid"] = eid;
	 data["etype"] = etype;
	 data =  JSON.stringify(data);
	 data ="forward="+encodeURIComponent(data);
	 $.ajax({
  	  url:ve_serv,
  	  async:true,
  	  data:data,
  	  dataType:"json",
  	  type:"post",
      success:function(result){
    	  $(".dms .dmList").html("");
          var containers = new Array();
//    	  for(i=0;i<result.length;i++){
          for(i=result.length-1;i>=0;i--){
    		var item = result[i];
		    var dmtype = item.dmtype;
		    var dmid = item.dmid;
		    var inverse = item.inverse;
		    var name = item.name;
		    var vtype = item.vtype;
		    var arity = item.arity;
		    var funct = item.functional;
		    var hasAuthor =item.hasAuthor; 
		    var li = addDMToLeftPanel(dmtype,dmid,arity,inverse,vtype,funct,hasAuthor,name,0) ;
		    containers.push(li) ;
    	  }
    	  for(i=0;i<containers.length;i++){
    		  fetchValueByContainer(containers[i].find(".li-container"),eid);
    	  }
      }
    });
}

function filterDMByMyGroup(groupID,lang,etype,eid,isInner,cid){
	$(".dms .dmList").html("");
	 var data={};
	 data["gid"]=groupID;
	 data["lang"] = lang;
	 data["eid"] = eid;
	 data["etype"] = etype;
	 data["isInner"]=isInner;
	 data["cid"]=cid;
	 data =  JSON.stringify(data);
	 data ="mygroup="+encodeURIComponent(data);
	 $.ajax({
 	  url:ve_serv,
 	  async:true,
 	  data:data,
 	  dataType:"json",
 	  type:"post",
     success:function(result){
    	 $(".dms .dmList").html("");
         var containers = new Array();
//   	     for(i=0;i<result.length;i++){
         for(i=result.length-1;i>=0;i--){
   		    var item = result[i];
		    var dmtype = item.dmtype;
		    var dmid = item.dmid;
		    var inverse = item.inverse;
		    var name = item.name;
		    var vtype = item.vtype;
		    var arity = item.arity;
		    var funct = item.functional;
		    var hasAuthor =item.hasAuthor; 
		    var li = addDMToLeftPanel(dmtype,dmid,arity,inverse,vtype,funct,hasAuthor,name,0) ;
		    containers.push(li) ;
   	     }
   	     for(i=0;i<containers.length;i++){
   		  fetchValueByContainer(containers[i].find(".li-container"),eid);
   	     }
     }
   });
}


function filterDMByOtherGroup(groupID,lang,etype,eid,isInner,cid){
	$(".dms .dmList").html("");
	 var data={};
	 data["gid"]=groupID;
	 data["lang"] = lang;
	 data["eid"] = eid;
	 data["etype"] = etype;
	 data["isInner"]=isInner;
	 data["cid"]=cid;
	 data =  JSON.stringify(data);
	 data ="othergroups="+encodeURIComponent(data);
	 $.ajax({
 	  url:ve_serv,
 	  async:true,
 	  data:data,
 	  dataType:"json",
 	  type:"post",
     success:function(result){
    	 $(".dms .dmList").html("");
        var containers = new Array();
//   	for(i=0;i<result.length;i++){
        for(i=result.length-1;i>=0;i--){
   		    var item = result[i];
		    var dmtype = item.dmtype;
		    var dmid = item.dmid;
		    var inverse = item.inverse;
		    var name = item.name;
		    var vtype = item.vtype;
		    var arity = item.arity;
		    var funct = item.functional;
		    var hasAuthor =item.hasAuthor; 
		    var li = addDMToLeftPanel(dmtype,dmid,arity,inverse,vtype,funct,hasAuthor,name,0) ;
		    containers.push(li) ;
   	  }
   	  for(i=0;i<containers.length;i++){
   		  fetchValueByContainer(containers[i].find(".li-container"),eid);
   	  }
     }
   });
}


function getAvailableChain(container,array){
	 var data={};
	 data["entity"] = array;
	 data["lang"] = displayLang;
	 data =  JSON.stringify(data);
	 data ="availableChainLink="+encodeURIComponent(data);
	 $.ajax({
	   	  url:ve_serv,
	   	  async:true,
	   	  data:data,
	   	  dataType:"json",
	   	  type:"post",
	   	  beforeSend:function(){
	   		  $(container).addClass("loading2");
	   	  },
	      success:function(result){
	    	  $(container).removeClass("loading2");
	    	  $(container).html("");
	  		  for(i=0;i<result.length;i++){
	  			  var item = result[i];
	  			  var name = item["name"] ;
	  			  var dmtype = item["dmtype"] ;
	  			  var dmid = item["dmid"];
	  			  var vtype = item["vtype"] ;
	  			  var inverse = item["inverse"];
	  			  var a=$("<a href='javascript:void(0)' class='linkName'></a>").html(name);
	  			  a.attr("dmtype",dmtype);
	  			  a.attr("dmid",dmid);
	  			  a.attr("vtype",vtype);
	  			 a.attr("inverse",inverse);
	  			  var li = $("<li class='relative'></li>").append(a);
		  		  var gspan =$("<span class='lcb'></span>");
		  		  var ga = $("<a href='javascript:void(0)' class='lchain'></a>").append(gspan) ;
		  		  var op_title=null;
	  			  if(displayLang=="en")
	  				   op_title = "Run";
	  			  else if(displayLang=="zh")
	  				   op_title = "执行"; 
	  			  ga.attr("title",op_title);
	  		      li.append(ga);
	  		      $(container).append(li);
	  		  }
	  		  
	       	  $(container).find("li:last").addClass("final");
	       }
	     });
}

function getMID(){
    count = count+1;
    return count-1;
}

//show the exist datammeber in the left and right panel
//show the exist view name in the text input
function init(){
	/*search data items*/
	/*input hints*/
	//quick search widget
  	$.widget( "custom.mycomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var that = this;
			currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					var ctext = item.category;
					if(ctext=="mygroup"){
						ctext = "my group";
					}else if(ctext=="othergroups"){
						ctext = "other groups";
					}
					var li = $("<li class='ui-autocomplete-category'></li>");
					li.text(ctext);
					li.attr("category",item.category);
					ul.append(li);
					currentCategory = item.category;
				}
				that._renderItemData( ul, item );
			});
//			$(".ui-autocomplete-category").live("click",function(){
//				var label = $(this).attr("category");
//				if(label=="forward"||label=="前向属性"){
//					filterDMByForward(displayLang,etype,eid);
//				}
//				else if(label=="backward"||label=="后向属性"){
//					filterDMByBackward(displayLang,etype,eid);
//				}
//				else if(label=="mygroup"||label=="我的组"){
//					filterDMByMyGroup(groupID,displayLang,etype,eid,isInner,editClassID);
//				}
//				else if(label=="othergroups"||label=="其它组"){
//					filterDMByOtherGroup(groupID,displayLang,etype,eid,isInner,editClassID);
//				}
//
////			    $(".qitem-box-inview .dmsearch").val(name);
//			    $(".qitem-box-inview .dmsearch").removeClass("focus");
//			    $(".qitem-box-inview .dmsearch").mycomplete("close");
//			});
		},
		_renderItemData:function( ul, item ) {
		    var dmtype = item.dmtype;
		    var dmid = item.dmid;
		    var inverse = item.inverse;
		    var name = item.name;
		    var vtype = item.vtype;
		    var arity = item.arity;
		    var funct = item.functional;
		    var hasAuthor =item.hasAuthor;
		    var category = item.category;
		
		    var li = showDMSearchItem(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor);//showMycompleteItem(vid,name,category);
			li.appendTo(ul);
			ul.find("li:last>div").addClass("final");
			return li;
		}
	});
	$(".qitem-box-inview .dmsearch" ).mycomplete({
		source: function( request, response ) {
			 var data={};
			 data["kw"] = request.term;
			 data["lang"] = displayLang;
			 data["etype"] = etype;
			 data["eid"] = eid;
//			 var minTypeArray = getMinType();
			 var isInner = $("#isInner").val();//minTypeArray[0] ;
			 var classID = editClassID ;//minTypeArray[1] ;
			 data["isInner"] = isInner;
			 data["cid"] = classID ;
			 data["user"] = getUser();
			 data["groupID"] =groupID;
		     data =  JSON.stringify(data);
			 data=("dmsearch="+encodeURIComponent(data));
			$.ajax({
				url: VESERV,//views_servlet,//
				dataType: "json",
				data: data,
				type:"post" ,
				success: function( data ) {
					response(data);
				}
			});
		},
		minLength:0
	}).focus(function () {
		if ($(this).mycomplete("widget").is(":visible")) {
             return;
        }
		$(this).mycomplete("search", $(this).val());
    });
//	$( "#search" ).autocomplete({
//		source: function( request, response ) {
//			 var data={};
//			 data["kw"] = request.term;
//			 data["lang"] = displayLang;
//			 data["etype"] = etype;
//			 data["eid"] = eid;
//			 data["isInner"] = isInner;
//			 data["cid"] = editClassID ;
//			 data["user"] = getUser();
//		     data =  JSON.stringify(data);
//			 data=("dmsearch="+encodeURIComponent(data));
//			$.ajax({
//				url: ve_serv,
//				dataType: "json",
//				data: data,
//				type:"post" ,
//				success: function( data ) {
//					response(data);
//				}
//			});
//		},
//		minLength:1
//		})
//	   .data( "autocomplete" )._renderItem = function( ul, item ) {
//		    var dmtype = item.dmtype;
//		    var dmid = item.dmid;
//		    var inverse = item.inverse;
//		    var name = item.name;
//		    var vtype = item.vtype;
//		    var arity = item.arity;
//		    var funct = item.functional;
//		    var hasAuthor =item.hasAuthor;
//		
//		    var li = showDMSearchItem(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor);
//			li.appendTo(ul);
//			ul.find("li:last>div").addClass("final");
//			return li;
//		};
	
	var box = $(".ruleList");
	if(query_item_id>0){
		addRules(query_item_id,box,true);
	}
	
	$(".ruleList .item,.tmpRuleList .item").live("mouseover",function(){
		$(this).addClass("hover");
	});
	
	$(".ruleList .item,.tmpRuleList .item").live("mouseout",function(){
		$(this).removeClass("hover");
	});	
	
	$(".dmName").change(function(){
		/*edit box*/
		$(".save_op").removeClass("disabled");
		
		var name = $(".dmName").val().trim();
		$(".tmpRuleList .item.target .ruleHead .pred").each(function(){
			$(this).html(name);
		});
	});
}

/**
 * @param dropEle. the .vcontent element
 * @param dragContainer. the div.li-container element
 */
function merge(dropEle,dragContainer){
	/*start:store the value map*/
	var hidden = $(".vcontent .hidden");
	var dmdiv = $("<div></div>").appendTo(hidden);
	dmdiv.attr("dmtype",$(dragContainer).attr("dmtype"));
	dmdiv.attr("dmid",$(dragContainer).attr("dmid"));
	dmdiv.html(dragContainer.parent().find(".li-container .content ul.pvalue").html());
	/*end:store the value map*/
	
	 //ui content
	var ul = $(dropEle).find(".pvalue");
	$(dropEle).find("li.final").removeClass("final");
    dragContainer.find(".pvalue>li").each(function(){
   	var etype = $(this).attr("etype");
   	var eid = $(this).attr("eid");
   	var xx=$(ul).find("li[etype="+etype+"][eid="+eid+"]").length;
   	if(xx>0)
         return;
   	else
   	  $(ul).append($(this).clone());
    });
    var mergeFrom= $(dragContainer).find(".titlebar>.title").html();
    var mergeTo = $(dropEle).find(".titlebar>.dm_name").html();
    var title=mergeFrom+"_or_"+mergeTo;
    
	// set inverse. value_type remain the same
	 $(dropEle).find(".edit_panel").attr("inverse",0);
	$(dropEle).find("li:last").addClass("final");
}

function editQueryItem(){
	var dmtype = CUSTOM_QUERY_ITEM;
	var dmid = query_item_id;
	var inverse =  0;
	var func  = 0;
	var vtype = value_type;
	var name = $("#name").val();
	createEditDMBox(name,dmtype,dmid,inverse,func,vtype);
}

function newQueryItem(){
	var name;
	if(displayLang=="en"){
		name = "untitled";
	}else if(displayLang=="zh"){
		name ="未命名";
	}
	var dmtype = -1;
	var dmid =-1;
	var inverse =0;
	var func  = 0;
	var vtype = 0;
	
	createEditDMBox(name,dmtype,dmid,inverse,func,vtype);
}

/*restore from chain operation*/
function restore(e){
	if($(e).parent().hasClass("chaining")){
		$(e).parent().removeClass("chaining");
		var titlebar = $(e).find(".titlebar");
	    addChainButtonToBar(titlebar);
//		titlebar.find(".header-chain").remove();
	    titlebar.removeClass("chainTitle");
		$(e).find(".pvalue").show();
		$(e).find(".op").show();
		$(e).find(".lvalue").remove();
		$(titlebar).find("a.restore").remove();
		$(titlebar).find("a.backchain").show();
	}
}

/*
 * save the current editing dm history : 
 * update the bases object and add in new Entity Object
 * 
 * */
function saveHistory(entity){
	//update the bases
	if(entity){
		var mid= entity.getMId();
		bases.push(mid);
		hashMap.put(mid, entity);
	}
}

/*create the html of li and bind events
 * return the li
 * */
function showDMSearchItem(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor){
	var li = $("<li class='hitem lentity'></li>");
	var div = $('<div class="split"></div>');
	
	var a = $('<a href="javascript:void(0)"></a>');
	a.attr("dmtype",dmtype) ;		
	a.attr("dmid",dmid) ;	
	div.append(a);
	
	a.click(function(){
		addDMToLeftPanel(dmtype,dmid,arity,inverse,vtype,funct,hasAuthor,name,1);
//	    $( "#search" ).autocomplete("close");
	    $(".qitem-box-inview .dmsearch").val(name);
	    $(".qitem-box-inview .dmsearch").removeClass("focus");
	    $(".qitem-box-inview .dmsearch").mycomplete("close");
	});
	
	var spanName = $("<span class='entity'></span>") ;
	spanName.text(name);
	a.append(spanName);
	li.append(div);
	return li;
}

function addRules(dmid,box,isSave){
	if(dmid<=0)
		return;
	 var data={};
	 data["dmid"] = dmid;
	 data["lang"] = displayLang;
	 data =  JSON.stringify(data);
	 data ="ruleinfo="+encodeURIComponent(data);
	 $.ajax({
	   	  url:ve_serv,
	   	  async:true,
	   	  data:data,
	   	  dataType:"json",
	   	  type:"post",
	   	  success:function(result){
	   		 for(i=0;i<result.length;i++){
	   			 data = result[i];
	             var item = addRule(data,isSave);
	             box.append(item);
	   		 }
	   	  }
     });
}

function getRule(dmid){
	var ruleitem = $("<div class='item'></div>");
	if(dmid<=0)
		return ruleitem;
	 var data={};
	 data["dmid"] = dmid;
	 data["lang"] = displayLang;
	 data =  JSON.stringify(data);
	 data ="ruleinfo="+encodeURIComponent(data);
	 $.ajax({
	   	  url:ve_serv,
	   	  async:false,
	   	  data:data,
	   	  dataType:"json",
	   	  type:"post",
	   	  success:function(result){
	   		 for(i=0;i<result.length;i++){
	   			 data = result[i];
	             var item = addRule(data);
	             ruleitem = item;
	   		 }
	   	  }
     });
	 return ruleitem;
}

/**
 * add a rule info in the rule area
 * @param data. the rule json get from dmid 
 * @param box. the rule area
 * @param isSave.判断是否是保存的规则
 */
function addRule(data,isSave){
	var item = $("<div class='item'></div>");
	/* start: head */
	var head = data["head"];
	var spanHeader = $("<span class='ruleHead'></span>");
	item.append(spanHeader);
	var headatomSpan = createAtomSpan(head);
	spanHeader.append(headatomSpan);
	// rule sign
	var spanSign = $("<span class='sign'>&nbsp;:-&nbsp;</span>");
	spanHeader.append(spanSign);
	/* end:rule head */

	/* start: rule body */
	var spanBody = $("<span class='ruleBody'></span>");
	item.append(spanBody);
	var body = data.body;
	for (k = 0; k < body.length; k++) {
		var bodyAtom = body[k];
		var bodyatomSpan = createAtomSpan(bodyAtom);
		spanBody.append(bodyatomSpan);
		if (k < body.length - 1)
			spanBody.append($("<span>&nbsp;,&nbsp;</span>"));
	}
	var spanFullStop = $("<span>&nbsp;.</span>");
	spanBody.append(spanFullStop);
	/* end:rule body */	
	
	if(isSave){
		//表示保存的规则
		item.addClass("saved_rule");
		var rows = data["rows"];
		var istarget = data["isTarget"];
		if(istarget){
			item.addClass("target");
			var delRule = $("<a class='del_rule_op'><span class='del_span'></span></a>");
			if(displayLang=="en"){
				delRule.attr("title","Delete this assignment");
			}else if(displayLang=="zh"){
				delRule.attr("title","删除这个赋值");
			}
			item.append(delRule);
			for(k=0;k<rows.length;k++){
				var hidden = $("<input type='hidden' />");
				hidden.val(rows[k]);
				item.append(hidden);
			} 
	    }
	}
	return item;
}

function createAtomSpan(atom){
	var resSpan  = $("<span></span>");
	//pred
    var spanPred = $("<span class='pred'></span>");
	var isInner = atom.isInner;
	var title = atom.title;
	var label = atom.label;
	var dmid = atom.dmid;
	spanPred.html(label);
	if(isInner==false){
		spanPred.attr("title",title);
		spanPred.addClass("outer");
	}else{
		spanPred.attr("title",label);
		spanPred.addClass("isInner");
	}
	
	resSpan.append(spanPred);
		 
	//pred args
	var termArray = atom.args;
	var spanArgs= $("<span class='args'></span>");
	spanArgs.append($("<span>(</span>"));
	for(j=0;j<termArray.length;j++){
		var term  = termArray[j];
		var spanTerm = $("<span></span>").html(term);
		spanArgs.append(spanTerm);
		if(j<termArray.length-1){
			spanArgs.append($("<span> , </span>"));
		}
	}
	spanArgs.append($("<span>)</span>"));
	resSpan.append(spanArgs);
    return resSpan;
}

function storeDM(name,dmtype,dmid,vtype){
	var dmbases = new Array();
	for(i=0;i<bases.length;i++){
		var mid = bases[i];
		var entity = hashMap.get(mid);
		if(entity!=null){
			var isOrigin = entity.isOrigin();
			var dtype = entity.getDMType();
			var did = entity.getDMID();
			var inverse = entity.getInverse();
			var item = new Object();
			item["dmtype"] = dtype;
			item["dmid"] = did;
			item["inverse"]=inverse;
			item["origin"]=isOrigin;
			dmbases.push(item);
		}
	}
	
	 var result ;
	 var data={};
	 data["name"] = name;
	 data["groupID"] = groupID;
	 data["isInner"] = isInner;
	 data["classID"] =editClassID;
	 data["lang"] =displayLang;
	 data["dmtype"] = dmtype;
	 data["dmid"]  = dmid;
	 data["bases"] = dmbases;
	 data["vtype"] = vtype;
	 data["userName"] = getUser();
	 data =  JSON.stringify(data);
	 data ="storedm="+encodeURIComponent(data);
	 
	 $.ajax({
	   	  url:ve_serv,
	   	  async:false,
	   	  data:data,
	   	  dataType:"json",
	   	  type:"post",
	   	  beforeSend:function(){
	   		  var div = $("<div class='load-data2'></div>");
	   		  $("body").append(div);
	   	  },
	   	  success:function(data){
	   		  $("body").find(".load-data2").remove();
	   		  result =  data;
	   	  }
     });
	 return result;
}
